<template>
    <HeaderTitle :textObj="textObj" @add="onAdd" right-text="新增"></HeaderTitle>

    <!-- 表格内容 -->
    <el-table :data="tableData" style="width: 100%" class="mt-10" stripe border>
        <el-table-column align="center" prop="id" label="编号" />
        <el-table-column align="center" :formatter="formatDate" prop="cTime" label="创建日期" />
        <el-table-column align="center" :formatter="formatDate" prop="uTime" label="更新日期" />
        <el-table-column align="center" prop="name" label="名字" />
        <el-table-column align="center" prop="unit" label="单位" />
        <el-table-column align="center" label="操作">
            <template #default="scope">
                <el-button :icon="Edit" type="primary" @click="handleEdit(scope.index, scope.row)" circle>
                </el-button>
                <el-button :icon="Delete" type="danger" @click="handleDelete(scope.index, scope.row)" circle>
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    

    <!-- 表单 -->
    <MyForm :show="show" ref="formRef" @submit="onSubmit" :editObj="editObj"></MyForm>

</template>

<script setup>
import HeaderTitle from '../../components/HeaderTitle.vue';
import { measurementList, measurementDel, measurementAdd, measurementEdit } from '@/api/index';
import { ref, onMounted } from 'vue';
import { formatDate } from '@/utils/utils';
import { Delete, Edit, } from '@element-plus/icons-vue';
import MyForm from './MyForm.vue';


let textObj = {
    module: '自定义类型',
    name: '测量类型',
    desc: '展示所有自定义的测量类型，提供了添加测量类型、修改测量类型、删除测量类型等功能.。',
}

const tableData = ref([
    // {
    //     "id": "510000199401275357",
    //     "cTime": 1666862547913,
    //     "uTime": 1666862617836,
    //     "name": "eee",
    //     "unit": "22"
    // }
])

// 显示对话框
// 获取子组件实例
const formRef = ref(null);
const onAdd = () => {
    // 新增的时候传一个空对象给form表单
    editObj.value = {};
    // 显示对话框
    formRef.value.show = true;
}

let editObj = ref({});
// 显示对话框, 传数据
let editIndex = -1;
const handleEdit = (index, row) => {
    editIndex = index;
    editObj.value = row;
    // 显示对话框
    formRef.value.show = true;
}

const handleDelete = (index, row) => {
    measurementDel({ id: row.id }).then(res => {
        tableData.value.splice(index, 1);
    }).catch((err) => {
        console.log(err);
    })
}

// 提交
const onSubmit = (data) => {
    // 先判断是添加还是编辑, 有id说明是在编辑
    if (data.id) {
        measurementEdit(data).then(res => {
            console.log('编辑成功');
            // 编辑成功后, 修改原对象
            // tableData[editIndex].value = data;
            tableData.value.splice(editIndex,1,data);
        })
    } else {
        measurementAdd(data).then(res => {
            // 新增成功后, 给列表添加一条数据
            tableData.value.unshift(res.data);
        })
    }
}

const getList = async () => {
    let res = await measurementList();
    tableData.value = res.data;
}

onMounted(getList);

</script>